from django.contrib.auth.models import User

from accounts.serializers import UserSeri
from common.serializers import ExcludeableSeri
from news.models import News


class NewsSeri(ExcludeableSeri):
    author = UserSeri(context={'excludes': ['teacher', 'student', 'schools', 'videos']}, required=False)

    def create(self, validated_data):
        username = validated_data.pop('author', {}).get('username', None)
        if username:
            author = User.objects.get(username=username)
            validated_data['author'] = author

        news = News(**validated_data)
        news.save()
        return news

    class Meta:
        model = News
        fields = ('pk', 'thumbnail', 'title', 'summary', 'link', 'create_date', 'author')